import { defineStore } from "pinia";
import { ref, computed } from "vue";
import Taro from "@tarojs/taro";
import {
  getDemographicInfo,
  createDemographicInfo,
  updateDemographicInfo,
  deleteDemographicInfo,
  getDemographicInfoList,
  type DemographicInfo,
  getNurseUserByPhone,
} from "../../../service/api/demographic";
import { queryById } from "../../../service/api/nurse_nurses";
import { localStg } from "@/utils";
import { getNurseUserByOpenId } from "@/pages/index/tooler";

/**
 * 人口统计学信息 Store
 * 管理人口统计学信息的状态和操作
 * 包含信息的存储、读取、根据电话获取信息等功能
 */
export const useDemographicInfoStore = defineStore("demographicInfo", () => {
  // 当前人口统计学信息
  const currentInfo = ref<DemographicInfo | null>(null);

  // 信息列表
  const infoList = ref<DemographicInfo[]>([]);

  // 当前健康管家信息
  const currentHealthButler = ref<any>(null);

  // 健康管家加载状态
  const loadingButler = ref(false);

  // 加载状态
  const loading = ref(false);

  // 错误信息
  const error = ref<string>("");

  const platform = ref<string>("");

  const setPlatform = (str: string) => {
    platform.value = str;
  };

  /**
   * 获取健康管家信息
   * @param butlerId 健康管家ID
   * @returns Promise<any | null>
   */
  const getHealthButlerById = async (butlerId: string): Promise<any | null> => {
    if (!butlerId) {
      console.warn("健康管家ID不能为空");
      return null;
    }

    loadingButler.value = true;

    try {
      const result = await queryById(butlerId);
      if (result && result.success) {
        currentHealthButler.value = result.success;
        console.log("获取健康管家信息成功:", result.success);
        return result.success;
      } else {
        console.warn("获取健康管家信息失败:", result);
        return null;
      }
    } catch (error) {
      console.error("获取健康管家信息失败:", error);
      return null;
    } finally {
      loadingButler.value = false;
    }
  };

  /**
   * 设置健康管家信息
   * @param butler 健康管家信息
   */
  const setHealthButler = (butler: any) => {
    currentHealthButler.value = butler;
  };

  /**
   * 清除健康管家信息
   */
  const clearHealthButler = () => {
    currentHealthButler.value = null;
  };

  /**
   * 更新健康管家ID并自动获取健康管家信息
   * @param healthId 健康管家ID
   * @returns Promise<boolean>
   */
  const updateHealthButlerId = async (healthId: string): Promise<boolean> => {
    if (!currentInfo.value) {
      console.warn("当前人口统计学信息不存在");
      return false;
    }

    try {
      // 更新 currentInfo 中的 healthId
      (currentInfo.value as any).healthId = healthId;

      // 自动获取健康管家信息
      await getHealthButlerById(healthId);

      // 保存到本地存储
      localStg.set("demographicInfo", currentInfo.value);

      return true;
    } catch (error) {
      console.error("更新健康管家ID失败:", error);
      return false;
    }
  };

  const setInfoByOpenId = async (openid: string, phone: string) => {
    const success= await getNurseUserByOpenId(openid, phone);
    console.log(`openid${openid}获取用户信息`);
    console.log(success);

    currentInfo.value = {
      ...(success || {}),
      idNumber: (success as any)?.idcard || "",
      healthId: (success as any)?.healthId || "",
      tel: (success as any)?.phone || "",
    } as unknown as DemographicInfo;
    console.log("currentInfo ---- 123", currentInfo.value);

    const nurseUser = await getNurseUser(phone);
    (currentInfo.value as any).idNumber = nurseUser?.idcard || "";

    // 自动获取健康管家信息
    const healthId = (currentInfo.value as any)?.healthId;
    if (healthId) {
      console.log("自动获取健康管家信息，ID:", healthId);
      await getHealthButlerById(healthId);
    }

    // 保存到本地存储
    localStg.set("demographicInfo", currentInfo.value);
  };

  /**
   * 根据电话号码获取人口统计学信息
   * @param phone 电话号码
   * @returns Promise<DemographicInfo | null>
   */
  const getDemographicInfoByPhone = async (phone: string): Promise<DemographicInfo | null> => {
    if (!phone) {
      error.value = "电话号码不能为空";
      return null;
    }

    loading.value = true;
    error.value = "";

    try {
      const { error, success } = await getDemographicInfo(phone);
      console.log(`电话${phone}获取人口统计学信息`);
      console.log(success);
      if (success?.records?.length > 0) {
        currentInfo.value = success.records[0];

        const nurseUser = await getNurseUser(phone);
        (currentInfo.value as any).idNumber = nurseUser?.idcard || "";

        // 自动获取健康管家信息
        const healthId = (currentInfo.value as any)?.healthId;
        if (healthId) {
          console.log("自动获取健康管家信息，ID:", healthId);
          await getHealthButlerById(healthId);
        }

        // 保存到本地存储
        localStg.set("demographicInfo", currentInfo.value);
        return currentInfo.value;
      } else {
        // error.value = error || '获取人口统计学信息失败'
        console.error("获取人口统计学信息失败:", error);
        return null;
      }
    } catch (err: any) {
      error.value = err.message || "网络请求失败";
      console.error("获取人口统计学信息失败:", err);
      return null;
    } finally {
      loading.value = false;
    }
  };
  const getNurseUser = async (phone: string) => {
    const { error, success } = await getNurseUserByPhone(phone);
    console.log(`电话${phone}获取用户信息`);
    console.log(success);
    if (success?.records?.length > 0) {
      return success.records.find((item: any) => item.idcard);
    } else {
      if (error && error.value !== undefined) {
        error.value = error.value || "获取用户信息失败";
      }
      return null;
    }
  };

  /**
   * 写入人口统计学信息
   * @param info 人口统计学信息
   * @returns Promise<boolean>
   */
  const setDemographicInfo = async (info: Omit<DemographicInfo, "id" | "createdAt" | "updatedAt">): Promise<boolean> => {
    if (!info.phone) {
      error.value = "电话号码不能为空";
      return false;
    }

    loading.value = true;
    error.value = "";

    try {
      const response = await createDemographicInfo(info);

      if (response.code === 0 && response.data) {
        currentInfo.value = response.data;
        // 保存到本地存储
        Taro.setStorageSync("demographicInfo", response.data);
        return true;
      } else {
        error.value = response.message || "保存信息失败";
        return false;
      }
    } catch (err: any) {
      error.value = err.message || "网络请求失败";
      console.error("保存人口统计学信息失败:", err);
      return false;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 更新人口统计学信息
   * @param info 人口统计学信息
   * @returns Promise<boolean>
   */
  const updateDemographicInfoData = async (info: DemographicInfo): Promise<boolean> => {
    if (!info.id) {
      error.value = "信息ID不能为空";
      return false;
    }

    loading.value = true;
    error.value = "";

    try {
      const response = await updateDemographicInfo(info);

      if (response.code === 0 && response.data) {
        currentInfo.value = response.data;
        // 更新本地存储
        Taro.setStorageSync("demographicInfo", response.data);
        return true;
      } else {
        error.value = response.message || "更新信息失败";
        return false;
      }
    } catch (err: any) {
      error.value = err.message || "网络请求失败";
      console.error("更新人口统计学信息失败:", err);
      return false;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 读取人口统计学信息（从本地存储）
   * @returns DemographicInfo | null
   */
  const getDemographicInfoFromStorage = (): DemographicInfo | null => {
    try {
      const storedInfo = Taro.getStorageSync("demographicInfo");
      if (storedInfo) {
        currentInfo.value = storedInfo;
        return storedInfo;
      }
      return null;
    } catch (err) {
      console.error("读取本地人口统计学信息失败:", err);
      return null;
    }
  };

  /**
   * 清除人口统计学信息
   */
  const clearDemographicInfo = () => {
    currentInfo.value = null;
    error.value = "";
    // 清除本地存储
    Taro.removeStorageSync("demographicInfo");
  };

  /**
   * 获取信息列表
   * @param params 查询参数
   * @returns Promise<boolean>
   */
  const fetchDemographicInfoList = async (
    params: {
      pageNo?: number;
      pageSize?: number;
      phone?: string;
      name?: string;
    } = {}
  ): Promise<boolean> => {
    loading.value = true;
    error.value = "";

    try {
      const response = await getDemographicInfoList(params);

      if (response.code === 0 && response.data) {
        infoList.value = response.data.list || [];
        return true;
      } else {
        error.value = response.message || "获取列表失败";
        return false;
      }
    } catch (err: any) {
      error.value = err.message || "网络请求失败";
      console.error("获取人口统计学信息列表失败:", err);
      return false;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 删除人口统计学信息
   * @param id 信息ID
   * @returns Promise<boolean>
   */
  const removeDemographicInfo = async (id: string): Promise<boolean> => {
    if (!id) {
      error.value = "信息ID不能为空";
      return false;
    }

    loading.value = true;
    error.value = "";

    try {
      const response = await deleteDemographicInfo(id);

      if (response.code === 0) {
        // 如果删除的是当前信息，则清除当前信息
        if (currentInfo.value?.id === id) {
          clearDemographicInfo();
        }
        // 从列表中移除
        infoList.value = infoList.value.filter((item) => item.id !== id);
        return true;
      } else {
        error.value = response.message || "删除信息失败";
        return false;
      }
    } catch (err: any) {
      error.value = err.message || "网络请求失败";
      console.error("删除人口统计学信息失败:", err);
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 计算属性
  const hasInfo = computed(() => !!currentInfo.value);
  const isPhoneValid = computed(() => {
    if (!currentInfo.value?.phone) return false;
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(currentInfo.value.phone);
  });

  return {
    // 状态
    currentInfo,
    infoList,
    currentHealthButler,
    loadingButler,
    loading,
    error,
    hasInfo,
    isPhoneValid,
    platform,
    setPlatform,

    // 方法
    getDemographicInfoByPhone,
    setDemographicInfo,
    updateDemographicInfoData,
    getDemographicInfoFromStorage,
    clearDemographicInfo,
    fetchDemographicInfoList,
    removeDemographicInfo,
    setInfoByOpenId,

    // 健康管家相关方法
    getHealthButlerById,
    setHealthButler,
    clearHealthButler,
    updateHealthButlerId,
  };
});
